package com.ahy231.service.impl;

import com.ahy231.entity.User;
import com.ahy231.mapper.LoginMapper;
import com.ahy231.service.LoginService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author ahy231
 * @date 2021/7/26 18:25
 * @description
 */
@Service
public class LoginServiceImpl implements LoginService {

    private final LoginMapper loginMapper;
    private final RedisTemplate<String, Object> redisTemplate;

    public LoginServiceImpl(LoginMapper loginMapper, RedisTemplate<String, Object> redisTemplate) {
        this.loginMapper = loginMapper;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean isUserExisting(long userId) {
        return loginMapper.selectCount(new QueryWrapper<User>().eq("user_id", userId)) > 0;
    }

    @Override
    @SuppressWarnings({"unchecked", "rawtypes"})
    public Set<String> getRolesByUserId(long userId) {
        Set<String> roles = null;
        // 从 redis 查
        if (Boolean.TRUE.equals(redisTemplate.hasKey(userId + ""))) {
            roles = (Set<String>) (Set) redisTemplate.opsForSet().members(userId + "");
        }
        // 从数据库查
        if (roles == null) {
            roles = new HashSet<>(loginMapper.getRolesByUserId(userId));
            Assert.notNull(roles, "数据库中查询不到 OpenId 为 " + userId + " 的用户对应的角色");
            redisTemplate.opsForSet().add(userId + "", roles.toArray());
            redisTemplate.expire(userId + "", 1000 * 60 * 60 * 5, TimeUnit.MILLISECONDS); // 设置过期时间为 5 小时
        }
        return roles;
    }
}
